<template>
  <div class="myContainer">
    <!-- 头部标题 start -->  
    <el-row class="myHeadeTitle">
      <el-col :span="12" class="myLineHeight_35px">
        {{title}}
      </el-col>
      <el-col :span="12" class="myTextAlignRight">
        <a id="downlink"></a>
        <el-button type="primary" class="myBgGreen" @click="onExport" :loading="loadingExport">导出Excel</el-button>
      </el-col>
    </el-row>
    <!-- 头部标题 end -->
    <!-- 搜索部分 start -->
    <el-row :gutter="10">
      <el-col :span="7">
        <template>
          <el-cascader
            placeholder="全部项目/小区"
            :options="regionOptions"
            v-model="regionOptSelected"
            ></el-cascader>
          </el-select>
        </template>
      </el-col>
      <el-col :span="8">
        <el-date-picker
          v-model="time"
          type="daterange"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-col>
      <el-col :span="3">
        <el-input v-model="kw" placeholder="请输入关键词"></el-input>
      </el-col>
      <el-col :span="3">
        <el-button class="myBgGreen" @click="onSearchKW">查询</el-button>
      </el-col>
    </el-row>
    <!-- 搜索部分 end -->
    <!-- 数据列表 start -->
    <div class="myPaddingTop_10px">
      <template>
        <el-table
          :data="tableDataList"
          border
          stripe
          v-loading="loading"
          @selection-change="handleSelectionChange"
          style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            width="100">
          </el-table-column>
          <el-table-column
            prop="plan_id"
            label="计划id">
          </el-table-column>
          <el-table-column
            prop="name"
            label="任务名称">
          </el-table-column>
          <el-table-column
            prop="date"
            width="150"
            label="巡检日期">
          </el-table-column>
          <el-table-column
            prop="complete_count"
            width="100"
            label="完成次数">
          </el-table-column>
          <el-table-column
            prop="area_name"
            label="所属小区">
          </el-table-column>
          <el-table-column
            width="100"
            label="操作">
            <template scope="scope">
              <el-button class="look" type="text" size="small" @click="onGetDetail(scope.row.plan_id,scope.row.date)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </div>
    <!-- 数据列表 end -->
    <!-- 分页控件 start -->
    <div class="block">                    
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page_num"
        :page-sizes="[10, 15]"
        :page-size="page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 分页控件 end -->
  </div>
</template>  

<style scoped>
  .myContainer{
    background: #fff;
    padding: 10px;
  }
  .myHeadeTitle{
    color: #000;
    font-weight: 500;
    font-size: 16px;
    padding-bottom: 5px;
    border-bottom: 1px solid #dbdbdb;
    margin-bottom:10px; 
  }
  .myHeadeTitle:before,.myHeadeTitle:after{
    content: " ";
    display: block;
    clear: both;
  }
  .myBgGreen{
    background: #00c2a9;
    border-color: #00c2a9;
    color: #fff;
    margin-top: 2px;
  }
  .myLineHeight_35px{
    line-height: 35px;
  }
  .myTextAlignRight{
    text-align: right;
  }
  .myBgGreen:hover{
    background: #33ceba;
  }
  .myPaddingTop_10px{
    padding-top: 10px;
  }
</style>

<script>
  import { getModelManageList , getInspectionTaskList , keyMapping } from '@/api/routinginspectionplan';
  import { getRegion } from '@/utils/localstorage';
  import { extractAreaIds } from '@/utils/misc';
  let XLSX = require('xlsx');

  export default {
     data(){
      return{
        title:"日常巡检任务管理",
        tableDataList:[],//数据列表
        page_size:10,
        page_num:1,
        total:null,
        regionOptions: [],
        regionOptSelected: [],
        kw:"",
        startTime:"",
        endTime:"",
        loading:false,
        time:[],
        loadingExport:false
      }
    },
    computed: {
      areaIds() {
        return extractAreaIds(this.regionOptSelected, this.regionOptions);
      }
    },
    mounted(){
      document.title = this.title;

      this.regionOptions = getRegion();
      this.regionOptSelected.push(this.regionOptions[0].value,this.regionOptions[0].children[0].value,this.regionOptions[0].children[0].children[0].value);
      
      this.onGetInspectionTaskList();

      this.outFile = document.getElementById('downlink');
    },
    methods:{
      handleSelectionChange(val) {//添加表格复选框【全选等功能】
        
      },
      handleSizeChange(val) {//每页条数控制
        this.page_size = val;
        this.onGetInspectionTaskList();
      },
      handleCurrentChange(val) {//每页
        this.page_num = val;
        this.onGetInspectionTaskList();
      },
      onSearchKW:function(){//关键词搜索
        this.onGetInspectionTaskList();
      },
      onGetDetail(plan_id,date){
        this.$router.push({
          path:'/inspectionTaskCountComponents',
          query: {id: plan_id,date:date}
        })
      },
      isArray(o){
        return Object.prototype.toString.call(o)=='[object Array]';
      },
      onGetInspectionTaskList(){//拉取任务列表
        let vm=this;
        vm.loading=true;
        if(vm.time){
          vm.startTime=vm.time[0];
          vm.endTime=vm.time[1];
        }else{
          vm.startTime="";
          vm.endTime="";
        }
        let params={
          area_id:vm.areaIds,
          start_date:vm.startTime,
          end_date:vm.endTime,
          keyword:vm.kw,
          page_size:vm.page_size,
          page_num:vm.page_num
        }
        getInspectionTaskList(vm.areaIds,params).then(response => {
          let res=response.data;
          vm.total=res.total;
          vm.page_num=res.page_num;
          vm.page_size=res.page_size;
          vm.tableDataList=res.rows;
          vm.loading=false;
          // console.log("yes",res)
        }).catch(error => {
          vm.loading=false;
          console.log("no",error)
        })
      },
      onExport(){
        let vm=this;
        let params={
          area_id:vm.areaIds,
          start_date:vm.time[0]||'',
          end_date:vm.time[1]||'',
          keyword:vm.kw,
          page_size:vm.total,
          page_num:vm.page_num
        }
        vm.loadingExport=true;
        getInspectionTaskList(vm.areaIds,params).then(response => {
          let res=response.data.rows;
          if(res.length==0){
            vm.loadingExport=false;
            vm.$message.info("没有可导出的数据！");
            return;
          }
          let data = [{}],name="日常巡检任务管理数据";
          for (let k in res[0]) {
            data[0][k] = k
          }
          data = data.concat(res);
          vm.downloadExl(data, name);
          vm.loadingExport=false;
          vm.$message.success(`导出成功！总共${res.length}条数据。`);
          // console.log("yes",res)
        }).catch(error => {
          vm.loadingExport=false;
          vm.$message.error("导出失败！");
          console.log("no",error)
        })
      },
      downloadExl: function (json, downName, type) {  // 导出到excel
        let keyMap = []
        for (let k in json[0]) {
          keyMap.push(k);
        }
        let tmpdata = [] 
        json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
          v: v[k],
          position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
        }))).reduce((prev, next) => prev.concat(next)).forEach(function (v) {
          tmpdata[v.position] = {
            v: keyMapping[v.v] || v.v
          }
        })
        let outputPos = Object.keys(tmpdata)  
        let tmpWB = {
          SheetNames: ['日常巡检任务管理数据'], 
          Sheets: {
            '日常巡检任务管理数据': Object.assign({},
              tmpdata, 
              {
                '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] 
              })
          }
        }
        let tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
          {bookType: (type === undefined ? 'xlsx' : type), bookSST: false, type: 'binary'} 
        ))], {
          type: ''
        }) 
        var href = URL.createObjectURL(tmpDown)  
        this.outFile.download = downName + '.xlsx'  
        this.outFile.href = href  
        this.outFile.click()  

        setTimeout(function () {  
          URL.revokeObjectURL(tmpDown) 
        }, 100)
      },
      s2ab: function (s) { 
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF
        }
        return buf
      },
      getCharCol: function (n) { 
        let s = ''
        let m = 0
        while (n > 0) {
          m = n % 26 + 1
          s = String.fromCharCode(m + 64) + s
          n = (n - m) / 26
        }
        return s
      }

    }
  }

</script>  



